package com.example.musicapp.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyApp extends Application {
    public static String sJSessionId;
    public static ThreadPoolExecutor sThreadPool;
    public static Context sContext;
    private static WeakReference<Activity> currentActivityWeakRef;
    private static final Object activityUpdateLock = new Object();

    @Override
    public void onCreate() {
        //我用了抛出策略
        super.onCreate();
        if (sContext == null){
            sContext = getApplicationContext();
        }




        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { }

            @Override
            public void onActivityStarted(@NonNull Activity activity) { }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                setCurrentActivity(activity);//设定当前Activity
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) { }

            @Override
            public void onActivityStopped(@NonNull Activity activity) { }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) { }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) { }
        });


    }



    public static ThreadPoolExecutor getThreadPool(){
        if(sThreadPool==null){
            sThreadPool = new ThreadPoolExecutor(5, 10,
                    100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10), new ThreadPoolExecutor.DiscardOldestPolicy());
        }
        return sThreadPool;
    }
    public static Context getContext(){


        return sContext;
    }
    /**
     * 获取当前栈顶的activity
     * @return 栈顶Activity
     */
    public static Activity getCurrentActivity() {
        synchronized (activityUpdateLock) {
            if (currentActivityWeakRef != null) {
                return currentActivityWeakRef.get();
            }
        }
        return null;
    }

    public static void setCurrentActivity(Activity activity) {
        synchronized (activityUpdateLock) {
            currentActivityWeakRef = new WeakReference<Activity>(activity);
        }
    }



}
